
import 'package:baby/Entities/DataContext.dart';
import 'package:baby/Entities/Name.dart';
import 'package:baby/Entities/Store/CartItem.dart';
import 'package:baby/Entities/Store/Product.dart';
import 'package:baby/Entities/Store/ProductCategory.dart';
import 'package:baby/StateManagement/ModelProvider.dart';
import 'package:baby/StateManagement/ObservableList.dart';
import 'package:baby/UI/Pages/StorePage/CartPage.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/widgets.dart';

import 'ProductViewer.dart';

class StorePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() => _StorePageState();
}

class _StorePageState extends State<StorePage> with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  TabController _controller;

  Future<MyObservableList<ProductCategory>> _loadDataFuture;

  Future<MyObservableList<ProductCategory>> _loadData(MyObservableList<ProductCategory> categories) async {
    if (categories.isNotEmpty) return categories;
    await Future.delayed(Duration(seconds: 1));
    categories.add(ProductCategory(
      name: Name(ug: "ھەممىسى"),
      products: MyObservableList()..addAll([
        Product(name: Name(ug: "بالىلار قۇۋۋەت ياڭىقى"), tag: "تاتلىق", price: 5.3, coverImage: "https://cdn.pixabay.com/photo/2019/06/03/17/56/background-4249442_960_720.jpg"),
        Product(name: Name(ug: "بالىلار ھەسىلى"), tag: "تۇزلۇق", price: 4.3, coverImage: "https://cdn.pixabay.com/photo/2015/10/26/11/10/honey-1006972_960_720.jpg"),
        Product(name: Name(ug: "بالىلار تورتى"), tag: "ئاچچىق", price: 7.3, coverImage: "https://cdn.pixabay.com/photo/2019/06/03/06/23/muffin-4248224_960_720.jpg"),
        Product(
          name: Name(ug: "بالىلار ئۇپىسى"),
          tag: "ئاپئاق ۋە پارقىراق",
          price: 7.3,
          coverImage: "https://cdn.pixabay.com/photo/2019/05/19/08/36/clay-4213487_960_720.jpg",
          description: "بالىلارنىڭ تىرىسىنى ئاق ھەم سۈزۈك قىلىدۇ، تىرىنىڭ كىيىم بىلەن سۈركىلىش ۋە يارىلىنىشىنىڭ ئۈنۈملۈك ئالدىنى ئالىدۇ.",
          images: [
            "https://cdn.pixabay.com/photo/2016/08/29/08/55/work-1627703_960_720.jpg",
            "https://cdn.pixabay.com/photo/2016/12/04/21/58/rabbit-1882699_960_720.jpg",
            "https://cdn.pixabay.com/photo/2019/05/29/09/41/sky-4237062_960_720.jpg",
            "https://cdn.pixabay.com/photo/2015/03/26/09/47/sky-690293_960_720.jpg",
            "https://cdn.pixabay.com/photo/2014/05/22/16/52/pyrenees-351266_960_720.jpg",
            "https://cdn.pixabay.com/photo/2019/06/07/17/28/cave-4258712_960_720.jpg"
          ],
          parameters: {
            "رەڭگى": "ئاق",
            "ماس كېلىدىغان ياشتىكى بالىلار": "0 < 5",
            "ئىشلەپ چىقارغۇچى": "سەبىيلەر بوۋاق شىركىتى",
            "يەنە دەيدىغىنىڭىز بارمۇ؟": "يىڭى يىلىڭلارغا مۇبارەك بولسۇن"
          }
        ),
        Product(name: Name(ug: "بۆلجۈرگەن"), tag: "چۈچۈمەل", price: 2.1, coverImage: "https://cdn.pixabay.com/photo/2017/11/29/16/12/raspberries-2986532_960_720.jpg"),
        Product(
            name: Name(ug: "بالىلار توشقىنى"),
            tag: "يۇڭلۇق",
            price: 9.3,
            coverImage: "https://cdn.pixabay.com/photo/2016/12/04/21/58/rabbit-1882699_960_720.jpg",
          description: "بالىڭىزغا ئېلىپ بەرسىڭىز پۇتىنى غاجىلىۋالىدۇ، گۈللىرىڭىزنى يەۋالىدۇ، قىچىپمۇ كىتىدۇ."
        ),
        Product(
            name: Name(ug: "بالىلار مۈشۈكى"),
            tag: "ئۇيقۇچان",
            price: 6.3,
            coverImage: "https://cdn.pixabay.com/photo/2014/04/13/20/49/cat-323262_960_720.jpg",
          description: "ئەمەلىيەتتە بۇ ئاسلانچاقنى سىتىۋالىمەن دەپ ئويلىماڭ، چۈنكى بىز سىزگە ساتقىلى ئۇنىمايمىز لول لول لول"
        ),
        Product(name: Name(ug: "بالىلار بۇغىسى"), tag: "تىز يۈگۈرىدۇ", price: 12.3, coverImage: "https://cdn.pixabay.com/photo/2019/06/05/14/27/forest-4253766_960_720.jpg"),
        Product(name: Name(ug: "قاتلىما"), tag: "يىيىشلىك", price: 5.0, coverImage: "https://cdn.pixabay.com/photo/2017/05/07/08/56/pancakes-2291908_960_720.jpg"),
      ])
    ));
    categories.add(ProductCategory(
      name: Name(ug: "كىيىم-كىچەك"),
    ));

    categories.add(ProductCategory(
      name: Name(ug: "يىمەكلىك"),
    ));

    categories.applyChanges();
    return categories;
  }

  @override
  Widget build(BuildContext context) {
    var categories = ModelContainer.of<DataContext>(context).model.productCategories;
    _loadDataFuture = _loadData(categories);

    return ModelDescendant<MyObservableList<ProductCategory>>(
      referenceModel: categories,
      onChanged: (context, _, data) {
        _controller = TabController(length: data.length, vsync: this);
        return FutureBuilder<MyObservableList<ProductCategory>>(
          future: _loadDataFuture,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              Widget widget = Scaffold(
                  appBar: AppBar(
                    actions: <Widget>[
                      IconButton(
                        icon: Icon(Icons.shopping_cart),
                        onPressed: () {
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) => CartPage()));
                        },
                      )
                    ],
                  ),
                  body: snapshot.data.isEmpty ? Center(child: Text("No data"),) : Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      TabBar(
                        isScrollable: true,
                        labelColor: Theme.of(context).primaryColor,
                        indicatorColor: Theme.of(context).primaryColor,
                        unselectedLabelColor: Colors.black.withOpacity(0.4),
                        controller: _controller,
                        tabs: data.map((category) => Tab(text: category.name.ug,)).toList(),
                      ),
                      Expanded(
                        child: TabBarView(
                          controller: _controller,
                          children: data.map((category) => ListView(
                            children: [
                              Wrap(children: category.products.map((product) => _buildProductItem(product: product)).toList(),)
                            ],
                          )).toList(),
                        ),
                      )
                    ],
                  )
              );
              /*
              widget = Directionality(
                textDirection: TextDirection.rtl,
                child: widget,
              );
              */
              return widget;
            }
            return Center(
              child: CircularProgressIndicator(),
            );
          },
        );
      },
    );
  }

  Widget _buildProductItem({@required Product product}){
    var paddingBottom = 50.0;
    Widget widget = Padding(
      padding: EdgeInsets.all(10.0),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(15.0),
        child: Container(
          width: 160.0,
          height: 230.0,
//          color: Colors.black.withOpacity(0.05),
          child: Stack(
            children: <Widget>[
              Positioned(
                top: 0.0,
                bottom: 0.0,
                left: 0.0,
                right: 0.0,
                child: Hero(
                  tag: product.guid,
                  child: CachedNetworkImage(imageUrl: product.coverImage, fit: BoxFit.cover,),
                )
              ),
              Positioned(
                left: 0.0,
                right: 0.0,
                height: 30.0,
                bottom: 0.0,
                child: Container(
                  color: Colors.black.withOpacity(0.25),
                  padding: EdgeInsets.symmetric(horizontal: 5.0),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text(product.name.ug, style: TextStyle(color: Colors.white),),
                      ),
                      Text(product.price.toString(), style: TextStyle(color: Colors.white),)
                    ],
                  )
                ),
              ),
            ],
          )
        ),
      ),
    );

    widget = InkWell(
      child: widget,
      onTap: () async {
        await Navigator.of(context).push<void>(MaterialPageRoute(
          builder: (context) => ProductViewer(
            product: product,
          )
        ));
//        var dataContext = ModelContainer.of<DataContext>(context).model;
//        dataContext.productsOfCart.add(CartItem(
//          count: 3.2,
//          product: product
//        ));
      },
    );

    return widget;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
